<template>
  <div class="detail">
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      right-text="首页"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <h3>{{ product.name }}</h3>
    <div class="content" v-html="product.content"></div>
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" @click="kefu" />
      <van-goods-action-icon
        icon="cart-o"
        :badge="cartCount"
        text="购物车"
        @click="toCart"
      />
      <van-goods-action-icon icon="shop-o" text="店铺" @click="toHome" />
      <van-goods-action-button
        type="danger"
        text="立即购买"
        @click="onClickButton"
      />
    </van-goods-action>
  </div>
</template>

<script>
import { Toast } from "vant"; // 轻提示
import { loadProductDetailAPI } from "../service/products";
import { mapGetters } from "vuex";
import { addToCart } from "../service/carts";
export default {
  data() {
    return {
      product: {},
    };
  },
  computed: {
    ...mapGetters(["cartCount"]),
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onClickRight() {
      this.$router.push({
        name: "Home",
      });
    },
    kefu() {
      Toast.success("客服暂未开通，敬请期待");
    },
    toCart() {
      this.$router.push({
        name: "Cart",
      });
    },
    toHome() {
      this.$router.push({
        name: "Home",
      });
    },
    async onClickButton() {
      // Toast.success("购买成功");
      await addToCart(this.product.id, 1, this.product.price);
      // dispatch 派发一个action 获取购物车信息
      this.$store.dispatch("loadCarts");
    },
  },
  // 根据 id 获取详情
  async created() {
    const productDetail = await loadProductDetailAPI(this.$route.params.id);
    this.product = productDetail.data;
  },
};
</script>

<style></style>
